package com.common.event.queue;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.common.event.EventMessage;
import com.common.event.ExecutorManager;
import com.common.event.listener.EventMessageListenerRouter;
/**
 * 
* @Title: Queue.java 
* @Package com.common.event.queue
* @Description: 队列抽象;具体实现目前有redis队列(可扩展其他的队列)
* @author tangzhibin
* @date 2017年3月22日 
* @version V1.0
 */
public abstract class Queue {
	
	public static final Logger	LOGGER	= LoggerFactory.getLogger(Queue.class);
	
	protected static final String COMMON_QUEUE_KEY="common_queue_";
	

	private  ExecutorManager executorManager;
	
	private  ScheduledExecutorService scheduled;
	
	private  int workerSize	= ExecutorManager.getPoolSize();
	
	private EventMessageListenerRouter eventListenerRouter;

	public void setEventListenerRouter(
			EventMessageListenerRouter eventListenerRouter) {
		this.eventListenerRouter = eventListenerRouter;
	}

	@PostConstruct
	public  void startQueueWorkerTask( ) {
		LOGGER.debug("Queue startQueueWorkerTask inited...");
		executorManager=new ExecutorManager(workerSize);
		scheduled = Executors.newScheduledThreadPool(1); 
		Queue queue=this;
		Thread starter=new Thread(new Runnable() {
			public void run() {
				LOGGER.debug("Queue  workers initing...");
				for (int i = 0; i < workerSize; i++) {
					try {
						executorManager.addTask(new QueueWorker(eventListenerRouter,queue));
					} catch (Exception e) {
						e.printStackTrace();
						LOGGER.error("Queue cosumer task error", e);
					}
				}
			}
		});
		starter.setDaemon(true);
		scheduled.schedule(starter,60,TimeUnit.SECONDS);
	}

	@PreDestroy
	public  void destory(){
		if(scheduled!=null){
			LOGGER.debug("Queue scheduled is closed...");
			scheduled.shutdownNow();
		}
		if(executorManager!=null){
			executorManager.shutdown();
		}
	}
	
	/**
	 * 入列
	 * @param eventMessage
	 * @return
	 */
	public abstract  boolean pushQueue( final EventMessage eventMessage);
	
	/**
	 * 出列
	 * @return EventMessage
	 */
	public abstract EventMessage popQueue();
	
	
}
